package zhenniu.best.webview.zhenniuwebview.utils;

import android.app.DownloadManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.util.Log;


import com.blankj.utilcode.util.SDCardUtils;
import com.blankj.utilcode.util.ToastUtils;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.Timer;
import java.util.TimerTask;

import zhenniu.best.webview.zhenniuwebview.ZhenNiu;
import zhenniu.best.webview.zhenniuwebview.bean.MessageEvent;
import zhenniu.best.webview.zhenniuwebview.global.Constants;

import static android.content.Context.DOWNLOAD_SERVICE;


/**
 * Created by Administrator on 2017/4/25.
 *
 */

public class DownloadUtils {
    public static final String ROOT_DIR = "Android/data/";
    public static final String DOWNLOAD_DIR = "Download";
    public static long APK_DOWNLOAD_ID = -1;
    private static Timer timer;
    private static TimerTask task;
    private static DownloadManager downloadManager;

    // 下载apk
    public static long downloadApk(String version, String url, String apkName) {
        String path = "";
        //判断sd卡是否能用
        if (SDCardUtils.isSDCardEnable()) {
//            if (!Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).exists()) {
//                Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).mkdir();// 创建保存目录
//            }
            //如果path是下面这样，那么setDestinationInExternalPublicDir(path, apkName)的路径是：/storge/emulated/0/storage/emulated/0/Download/期权屋.apk
//            path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath();

            //如果path是下面这样，那么setDestinationInExternalPublicDir(path, apkName)的路径是：/storage/emulated/0/Download/期权屋.apk
            //放在公共文件夹下，所以卸载app后，更新包也会一同被删除
            path = Environment.DIRECTORY_DOWNLOADS;

        } else {
            path = getDir(DOWNLOAD_DIR);
        }
        Log.w("aaa", "apk保存路径：\t\t\t" + path);
        // 删除以前下载的安装包
        //得到 request.setDestinationInExternalPublicDir(path, apkName)设置的下载路径：/storage/emulated/0/Download/期权屋.apk
        File externalStoragePublicDirectory = Environment.getExternalStoragePublicDirectory(path);
        //非空判断
        if (externalStoragePublicDirectory != null && externalStoragePublicDirectory.exists()) {
            //用路径生成个文件，判断时候有已下载号的apk
            File file1 = new File(externalStoragePublicDirectory.getAbsolutePath(), apkName);
            //有已经存在的apk那么就删除
            if (file1.exists() && file1.isFile()) {
                file1.delete();
            }
        }

        downloadManager = (DownloadManager) ZhenNiu.getContext().getSystemService(DOWNLOAD_SERVICE);
        DownloadManager.Request request = new DownloadManager.Request(Uri.parse(url));

        //下载apk包,路径 ：内部存储/storge/emulated/0/Download/下面，所以这里的path就不应该是Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).getAbsolutePath()，否则路径会变成 /storage/emulated/0/storage/emulated/0/Download/期权屋.apk, path应该是Environment.DIRECTORY_DOWNLOADS;
        //问题：file.exists() && file.isFile() 判断的并不是和下载的路径一样，它是/Download/下面，不带/storge/emulated/0/
        request.setDestinationInExternalPublicDir(path, apkName);
//        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_WIFI);// WiFi下下载
//        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE);
        request.setAllowedOverRoaming(true);// 允许漫游是下载
        request.setAllowedOverMetered(true);// 允许计量时网络下载
        request.allowScanningByMediaScanner();// 允许媒体扫描到这个文件
        // 设置通知标题、描述、显示状态
        request.setTitle(apkName);
        request.setDescription(version + "版");
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE);
        request.setMimeType(Constants.MIME_TYPE);
        request.setVisibleInDownloadsUi(true);
        //创建下载文件
        ToastUtils.showShort("下载开始");
        long downloadID = downloadManager.enqueue(request);
        getProgressValue(downloadID);
        return downloadID;// 执行下载并获取下载id
    }


    /**
     * 获取应用目录，当SD卡存在时，获取SD卡上的目录，当SD卡不存在时，获取应用的cache目录
     */
    public static String getDir(String name) {
        StringBuilder sb = new StringBuilder();
        if (SDCardUtils.isSDCardEnable()) {   //有SD卡
            sb.append(getExternalStoragePath());   //获取SD卡目录

        } else {   //没有SD卡
            sb.append(getCachePath());    //获取缓存目录
        }
        sb.append(name);
        sb.append(File.separator);
        String path = sb.toString();
        if (createDirs(path)) {
            return path;
        } else {
            return null;
        }
    }

    /**
     * 创建文件夹
     */
    public static boolean createDirs(String dirPath) {
        File file = new File(dirPath);
        if (!file.exists() || !file.isDirectory()) {
            if (file.mkdirs()) {
                return true;
            } else {
                if (!file.getParentFile().exists()) {
                    return file.getParentFile().mkdir();
                }
            }
        }
        return true;
    }

    /**
     * 获取SD下的应用目录
     */
    public static String getExternalStoragePath() {
        StringBuilder sb = new StringBuilder();
        sb.append(Environment.getExternalStorageDirectory().getAbsolutePath());
        sb.append(File.separator);
        sb.append(ROOT_DIR);
        sb.append(File.separator);
        return sb.toString();
    }


    /**
     * 获取应用的cache目录
     */
    public static String getCachePath() {
        File f = ZhenNiu.getContext().getCacheDir();
        if (null == f) {
            return null;
        } else {
            return f.getAbsolutePath() + "/";
        }
    }


    private static void getProgressValue(long id){
        final  DownloadManager.Query query = new DownloadManager.Query();
        query.setFilterById(id);
        final MessageEvent messageEvent = new MessageEvent();
        //根据id得到正在下载的是哪个
        timer = new Timer();
        task = new TimerTask() {
            @Override
            public void run() {
                Cursor cursor = downloadManager.query(query);
                if (cursor != null && cursor.moveToFirst()) {
                    int totalBytesIdx = cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_TOTAL_SIZE_BYTES);
                    if (cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS)) == DownloadManager.STATUS_SUCCESSFUL) {

                        //TODO 下载完成 进度值为100
                        messageEvent.setI(100);
                        EventBus.getDefault().post(messageEvent);
                        task.cancel();

                        //下载的文件到本地的目录
                        int fileUriIdx = cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI);
                        String fileUri = cursor.getString(fileUriIdx);
                        String filePath = null;

                        //打开安装apk的页面
                        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {
                            if (fileUri != null) {
                                filePath = Uri.parse(fileUri).getPath();
                            }
                        } else {
                            //Android 7.0以上的方式：请求获取写入权限，这一步报错
                            //过时的方式：DownloadManager.COLUMN_LOCAL_FILENAME
                            int fileNameIdx = cursor.getColumnIndex(DownloadManager.COLUMN_LOCAL_FILENAME);
                            filePath = cursor.getString(fileNameIdx);
                        }

                        AppUtils.installApp(filePath, "zhenniu.best.webview.zhenniuwebview.fileProvider");
                    }

//                    int downloadBytesIdx = cursor.getColumnIndexOrThrow(DownloadManager.COLUMN_BYTES_DOWNLOADED_SO_FAR);
//
//                    long downloadBytes = cursor.getLong(downloadBytesIdx);
////                    LogUtils.eTag("downloadBytes", downloadBytes + "");
//                    long totalBytes = cursor.getLong(totalBytesIdx);
////                    LogUtils.eTag("totalBytes", totalBytes + "");
//                    double pro = (downloadBytes  / totalBytes) * 100;
////                    LogUtils.eTag("answer", pro + "");
//                    //TODO 下载进度值实时更新
//                    messageEvent.setI(pro);
//                    EventBus.getDefault().post(messageEvent);
                }
                cursor.close();
            }
        };
        timer.schedule(task, 0,1000);
    }
}
